package com.jrowny.mediators
{
	import com.jrowny.enum.Notes;
	
	import com.jrowny.controls.SpriteElement;
	
	import com.jrowny.events.ElementEvent;
	
	import flash.display.Bitmap;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	
	import mx.collections.ArrayCollection;
	import mx.events.CollectionEvent;
	import mx.events.CollectionEventKind;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	import com.jrowny.proxy.ElementProxy;
	import components.ImageArea;
	
	public class ImageAreaMediator extends Mediator
	{
		public static const NAME:String = "ImageAreaMediator";
		public var elementProxy:ElementProxy;
		public function ImageAreaMediator(viewComponent:Object=null)
		{
			super(NAME, viewComponent);
			elementProxy = facade.retrieveProxy(ElementProxy.NAME) as ElementProxy;
			imageArea.elements = new ArrayCollection;
			imageArea.addEventListener(ElementEvent.ELEMENT_ADDED,onElementAdded);
			imageArea.addEventListener(ElementEvent.ELEMENT_CHANGED,onElementChanged);
			imageArea.addEventListener(ElementEvent.ELEMENT_SELECTED,onElementSelected);
			imageArea.addEventListener(ElementEvent.ELEMENT_DELETED,onElementDeleted);
		}
		public function get imageArea():ImageArea{
			return viewComponent as ImageArea;
		}
		
		/**
		 * view handlers
		 **/
		private function onElementChanged(event:ElementEvent):void{
			//let everyone know, the elements have been updated
			elementProxy.elements.dispatchEvent(
				new CollectionEvent(CollectionEvent.COLLECTION_CHANGE));
		}
		private function onElementDeleted(event:ElementEvent):void{
			elementProxy.removeElement(event.spriteElement);
		}
		private function onElementAdded(event:ElementEvent):void{
			elementProxy.addElement(event.spriteElement);
		}
		private function onElementSelected(event:ElementEvent):void{
			elementProxy.curElm = event.spriteElement;
		}
		/**
		 *  Handle notifications down here
		 **/		
		override public function listNotificationInterests():Array{
			return [Notes.IMAGE_LOADED,
					Notes.ELEMENT_SELECTED]
		}
		override public function handleNotification(notification:INotification):void{
			switch(notification.getName()){
				case Notes.IMAGE_LOADED:
					imageArea.imgSprite.source = notification.getBody() as Bitmap;
				break;
				case Notes.ELEMENT_SELECTED:
					imageArea.selectElm(notification.getBody() as SpriteElement);
				break;
			}
		}
	}
}